<template>
  <div id="empRelationUser">
    <el-form
      :model="userForm"
      ref="userFormRef"
      class="form-input-m"
      label-width="80px"
      :inline="true"
      @submit.native.prevent
    >
      <el-form-item label="选择用户">
        <el-select
          placeholder="请选择用户"
          :teleported="false"
          v-model="uservalue"
          @change="changeTitle"
          filterable
          style="width: 200px;"
        >
          <el-option
            v-for="user in userOptions"
            :key="user.id"
            :label="user.realname"
            :value="user.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" plain @click="handleAddRelation()">添加</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-button type="danger" plain @click="deleteEmployUsers">删除全部</el-button>
      </el-form-item>
    </el-form>

    <el-table
      class="empluserstable"
      ref="employUsersTable"
      v-loading="uloading"
      row-key="id"
      :data="employUsersList"
      style="width: 100%"
      highlight-current-row
      max-height="335px"
    >
      <el-table-column label="序号" width="60" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="username"
        label="用户名"
        min-width="150"
        align="left"
      ></el-table-column>

      <el-table-column prop="realname" label="名称" min-width="200" align="left"></el-table-column>

      <el-table-column fixed="right" label="操作" width="90" align="center">
        <template #default="scope">
          <el-button
            type="danger"
            icon="delete"
            plain
            circle
            @click="deleteEmployUser(scope.row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="dialog-footer flex justify-end">
      <el-button @click="closeRelationDialog('userFormRef')">关闭</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, watch, onMounted } from 'vue';
let { proxy }: any = getCurrentInstance();
import SelectByUserList from '@/components/SelectByUserList.vue'; //点击选择用户
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';

// 全局变量定义区 ==========
let uloading = ref(false);
let visibleUser = ref(false);
let uservalue = ref(''); //select接收值
let userForm = reactive({
  id: '',
  realname: ''
});

// const userFormRule = {
//   userName: [
//     {
//       required: true,
//       message: '请输入名称',
//       trigger: 'blur'
//     }
//   ]
// };

let employUsersList: any = reactive([]); //当前已关联关联用户列表(表格)
let userOptions: any = reactive([]);

let currentEmployeeId = ref('');
let contactTableList = reactive([]);

let childIds = reactive({
  orgId: '',
  deptId: ''
});

let employeeId = ''; //接收传过来的员工id

//暴露属性和方法
defineExpose({
  init
});

// 方法定义区 =============
function init(item: any) {
  // console.log('父组件传给关联用户子组件的机构和部门', item);
  if (item.id) {
    // 机构和部门id
    childIds.orgId = item.orgId;
    childIds.deptId = item.deptId ? item.deptId : '';
    employeeId = item.id; //员工id
  }
}

//选择用户的输入框改变
function bindUserList(value: any) {
  // const userBySelect: any = proxy.$refs.userBySelect;
  // userBySelect.userForm.name = value;
  // userBySelect.totalCount = 1;
  // userBySelect.findUserList();
}
//点击选择的用户
function selectUser(row: any) {
  //   userForm.id = row.id;
  //   userForm.name = row.name;
  //   userForm.userName = row.userName;
  //   userForm.userNameAndSurname = row.surname + row.name + '(' + row.userName + ')';
  //   const selectUserEle: any = proxy.$refs.selectUser;
  //   selectUserEle.focus();
  //   visibleUser.value = false;
}

//选择部门的输入框获取焦点
function showUserList(e: any) {
  // const userBySelect: any = proxy.$refs.userBySelect;
  // userBySelect.userForm.name = userForm.name;
  // userBySelect.userForm.id = userForm.id;
  // userBySelect.userForm.userName = userForm.userName;
  // userBySelect.totalCount = 1;
  // userBySelect.findUserList();
}

//按回车键选择组织机构列表的第一项
function onEnterSelectUser() {
  // const userBySelect: any = proxy.$refs.userBySelect;
  // if (userBySelect.userListInSelect && userBySelect.userListInSelect.length > 0) {
  //   selectUser(userBySelect.userListInSelect[0]);
  //   const selectUserEle: any = proxy.$refs.selectUser;
  //   selectUserEle.blur();
  // }
}

// 改变下拉框标题
function changeTitle(val: any) {
  userForm.id = val;
}

// 页面加载时
proxy.$nextTick(() => {
  getUserListByHisEmployeeId(employeeId); //表格

  getUserOptions(); //下拉框
});

// 获取所有用户选项 (下拉框)
function getUserOptions() {
  const url = '/api/user/getUserInfoList';
  proxy.$http
    .get(url, {})
    .then((res: any) => {
      userOptions.push(...res.data);
      // console.log('获取所有可用用户', userOptions);
    })
    .catch((err: any) => {
      VxeMessage('获取所有用户选项 (下拉框)失败', VxeNotifyType.error);
    });
}

// 获取当前员工下的已关联的所有用户(表格)
function getUserListByHisEmployeeId(id: any) {
  if (id) {
    const url = '/api/sys/hisEmployee/getUserListByHisEmployeeId/' + id;
    proxy.$http
      .get(url)
      .then((res: any) => {
        employUsersList.push(...res.data);
      })
      .catch((err: any) => {
        // VxeMessage('获取已关联的所有用户失败','error')
      });
  }
}

//   添加
function handleAddRelation() {
  // const $el = proxy.$refs.userForm;
  // $el.validate((valid: any) => {
  //   if (!valid) {
  //     return false;
  //   }
  // });
  //  // 员工id 用户id
  employUsersList.length = 0;
  const url = '/api/sys/hisEmployee/addContactUserInfo/' + employeeId + '/' + userForm.id;
  proxy.$http
    .put(url)
    .then((res: any) => {
      if (res.status.code === 400) {
        VxeMessage('添加关联用户失败', VxeNotifyType.error);
      } else {
        getUserListByHisEmployeeId(employeeId);
        userForm.id = '';
        userForm.realname = '';
        uservalue.value = ''; //清空选择框
        VxeMessage('添加关联用户成功', VxeNotifyType.success);
      }
    })
    .catch((err: any) => {
      VxeMessage('请选择要关联的用户异常', VxeNotifyType.warning);
    });
}

// 删除全部
const deleteEmployUsers = async () => {
  const type = await VXETable.modal.confirm('您确定要删除此员工关联的全部用户吗？');
  if (type === 'cancel') {
    // VXETable.modal.message({
    //   status: 'info',
    //   content: `点击了${type == 'cancel' ? '取消' : '确定'}`
    // });
  } else {
    employUsersList.length = 0;
    const url = '/api/sys/hisEmployee/deleteUserContactById/' + employeeId + '/1';
    proxy.$http
      .delete(url)
      .then((res: any) => {
        getUserListByHisEmployeeId(employeeId);
        if (res.status.code === 1) {
          VXETable.modal.message({
            content: '删除此员工关联的全部用户成功',
            status: 'success'
          });
        } else {
          VXETable.modal.message({
            content: '删除此员工关联的全部用户失败',
            status: 'error'
          });
        }
      })
      .catch((err: any) => {
        VxeMessage('删除全部用户接口失败', VxeNotifyType.error);
      });
  }
};

// 删除一个
const deleteEmployUser = async (id: any) => {
  const type = await VXETable.modal.confirm('您确定要删除此员工关联的这个用户吗？');
  if (type === 'cancel') {
    // VXETable.modal.message({
    //   status: 'info',
    //   content: `点击了${type == 'cancel' ? '取消' : '确定'}`
    // });
  } else {
    employUsersList.length = 0;
    const url = '/api/sys/hisEmployee/deleteUserContactById/' + id + '/0';
    proxy.$http
      .delete(url)
      .then((res: any) => {
        getUserListByHisEmployeeId(employeeId);
        if (res.status.code === 1) {
          VXETable.modal.message({
            content: '删除此员工关联的一个用户成功',
            status: 'success'
          });
        } else {
          VXETable.modal.message({
            content: '删除此员工关联的一个用户失败',
            status: 'error'
          });
        }
      })
      .catch((err: any) => {
        VxeMessage('删除一个用户接口失败', VxeNotifyType.error);
      });
  }
};

// 关闭弹框
function closeRelationDialog(formName: any) {
  // let el = proxy.$refs.form;
  proxy.$emit('closePerDialog');
}
</script>

<style lang="scss" scoped>
#empRelationUser {
  position: relative;
  height: 100%;
  .dialog-footer {
    position: absolute;
    bottom: 5px;
    right: 10px;
  }
}
</style>
